package com.simple.util.common;

import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.support.RequestContextUtils;

public class LocaleUtil {
	/** The Constant WEBSITE_LOCALE_DEFAULT. */
	public final static String WEBSITE_LOCALE_DEFAULT = SimplePropertyLoad.getInstance().getString(
	        "website.locale.default").trim();
	
	/** The Constant WEBSITE_LOCALE_ALL. */
	public final static String WEBSITE_LOCALE_ALL = SimplePropertyLoad.getInstance().getString(
	        "website.locale.all").trim();

	/**
	 * Gets the valid locale.
	 * 
	 * @param locale
	 *            the locale
	 * @return the valid locale
	 */
	public static String getValidLocale(final Locale locale) {
		String outLocale = WEBSITE_LOCALE_DEFAULT;
		final List<String> localeList = StringUtil.splitByTrim(WEBSITE_LOCALE_ALL, ",");
		for (final Iterator<String> iter = localeList.iterator(); iter.hasNext();) {
			final String tempLocale = (String) iter.next();
			if (locale.toString().equals(tempLocale)) {
				outLocale = locale.toString();
				break;
			}
		}
		return outLocale;
	}

	/**
	 * convert string to locale , such as "zh_CN" to Locale.
	 * 
	 * @param s
	 *            the s
	 * @return the locale
	 */
	public static Locale toLocaleFromStr(final String s) {
		Locale l;
		final String[] arr = s.split("_");
		if (arr.length == 1) {
			l = new Locale(arr[0]);
		} else if (arr.length == 2) {
			l = new Locale(arr[0], arr[1]);
		} else {
			l = new Locale(s);
		}

		return l;
	}
	
	
	public static String getLocaleFromRquest(final HttpServletRequest request) {
		return getValidLocale(RequestContextUtils.getLocale(request));
	}
}
